package com.xms.file.api.controller;

import com.xms.file.api.model.FileContentModel;
import com.xms.utils.FileUtil;
import com.xms.utils.StringUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * <p>
 * FileEditorController
 * </p>
 *
 * @author migo
 * @since 2021/11/10
 */
@RestController
@RequestMapping("/{org}/api/file/editor")
public class FileEditorController extends ApiBaseController {
    private static String FOLDER = ClassUtils.getDefaultClassLoader().getResource("").getPath();

    public FileEditorController() {

    }

    @ApiOperation("读取文件内容")
    @GetMapping("getcontent")
    public String getContent(@RequestParam(value = "filepath", required = true) String filepath) {
        if (StringUtil.isEmpty(filepath)) {
            return "请提供文件路径";
        }
        if(!filepath.endsWith(".html") && !filepath.endsWith(".js") && !filepath.endsWith(".css")){
            return "不允许编辑的文件类型";
        }
        return FileUtil.readFile(FOLDER + filepath);
    }

    @ApiOperation("保存文件内容")
    @PostMapping("save")
    public JsonResultObject save(@RequestBody FileContentModel model) throws IOException {
        if (StringUtil.isEmpty(model.filepath)) {
            return JNotSpecifiedParams("filepath");
        }
        if(!model.filepath.endsWith(".html") && !model.filepath.endsWith(".js") && !model.filepath.endsWith(".css")){
            return JSaveFailure("不允许编辑的文件类型");
        }
        FileUtil.writeFile(FOLDER + model.filepath, model.content);
        return JSaveSuccess();
    }
}
